// src/App.tsx
import React, { useState, useEffect, useRef } from "react";
import { Button, Slider, Select, Progress, notification } from "antd";
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
  SoundOutlined,
} from "@ant-design/icons";
import "./App.css";

const { Option } = Select;

// 音频资源URL
const SOUNDS = [
  {
    id: "rain",
    name: "雨天",
    url: `${process.env.PUBLIC_URL}/sounds/rain.m4a`,
  },
  {
    id: "cafe",
    name: "森林",
    url: `${process.env.PUBLIC_URL}/sounds/forest.mp4`,
  },
];

type TimerMode = "idle" | "work" | "break";

const App: React.FC = () => {
  // 状态管理
  const [workDuration, setWorkDuration] = useState<number>(25); // 分钟
  const [timeLeft, setTimeLeft] = useState<number>(25 * 60); // 秒
  const [isRunning, setIsRunning] = useState<boolean>(false);
  const [mode, setMode] = useState<TimerMode>("idle");
  const [selectedSound, setSelectedSound] = useState<string | null>(null);
  const [isSoundPlaying, setIsSoundPlaying] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);

  const audioRef = useRef<HTMLAudioElement | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const [api, contextHolder] = notification.useNotification({
    stack: { threshold: 1 },
  });
  // 请求通知权限
  useEffect(() => {
    if (
      Notification.permission !== "granted" &&
      Notification.permission !== "denied"
    ) {
      api.info({
        message: "通知权限",
        description: "请允许通知权限，以便在专注时间结束时收到提醒",
        showProgress: true,
        btn: (
          <Button
            type="primary"
            onClick={() => Notification.requestPermission()}
          >
            允许通知
          </Button>
        ),
      });
    }
  }, [api]);

  // 计时器逻辑
  useEffect(() => {
    if (isRunning) {
      intervalRef.current = setInterval(() => {
        setTimeLeft((prev) => {
          if (prev <= 1) {
            clearInterval(intervalRef.current!);
            // 当前模式结束
            if (mode === "work") {
              // 发送通知
              if (Notification.permission === "granted") {
                new Notification("专注时间结束", {
                  body: "休息5分钟开始！",
                  icon: "/favicon.ico",
                });
              }
              // 切换到休息模式
              setMode("break");
              setTimeLeft(5 * 60);
              return 5 * 60;
            } else if (mode === "break") {
              // 发送通知
              if (Notification.permission === "granted") {
                new Notification("休息时间结束", {
                  body: "新的专注时间开始！",
                  icon: "/favicon.ico",
                });
              }
              // 切换到工作模式
              setMode("work");
              setTimeLeft(workDuration * 60);
              return workDuration * 60;
            }
          }
          return prev - 1;
        });
      }, 1000);
    } else if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [isRunning, mode, workDuration]);

  // 更新进度
  useEffect(() => {
    const totalTime = mode === "work" ? workDuration * 60 : 5 * 60;
    const currentProgress = ((totalTime - timeLeft) / totalTime) * 100;
    setProgress(currentProgress);
  }, [timeLeft, mode, workDuration]);

  // 处理音频播放
  const handleSoundToggle = () => {
    if (!audioRef.current) return;

    if (isSoundPlaying) {
      audioRef.current.pause();
    } else {
      audioRef.current.play();
    }
    setIsSoundPlaying(!isSoundPlaying);
  };

  // 开始计时器
  const startTimer = () => {
    if (mode === "idle") {
      setMode("work");
      setTimeLeft(workDuration * 60);
    }
    setIsRunning(true);
  };

  // 暂停计时器
  const pauseTimer = () => {
    setIsRunning(false);
  };

  // 重置计时器
  const resetTimer = () => {
    setIsRunning(false);
    setMode("idle");
    setTimeLeft(workDuration * 60);
    setProgress(0);
  };

  // 格式化时间显示
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, "0")}:${secs
      .toString()
      .padStart(2, "0")}`;
  };

  // 获取当前模式名称
  const getModeName = (): string => {
    switch (mode) {
      case "work":
        return "专注工作";
      case "break":
        return "休息时间";
      default:
        return "准备开始";
    }
  };

  // 获取进度条颜色
  const getProgressColor = (): string => {
    switch (mode) {
      case "work":
        return "#1890ff";
      case "break":
        return "#52c41a";
      default:
        return "#d9d9d9";
    }
  };

  return (
    <div className={`app-container ${mode}`}>
      {contextHolder}
      {/* 背景音频元素 */}
      <audio
        ref={audioRef}
        src={selectedSound || undefined}
        loop
        onEnded={() => setIsSoundPlaying(false)}
      />

      <div className="timer-card">
        <div className="progress-container">
          <Progress
            type="circle"
            percent={progress}
            strokeColor={getProgressColor()}
            strokeWidth={8}
            trailColor="rgba(255,255,255,0.1)"
            size={280}
            format={() => (
              <div className="time-display">
                <div className="time">{formatTime(timeLeft)}</div>
                <div className="mode-label">{getModeName()}</div>
              </div>
            )}
          />
        </div>

        <div className="controls">
          {isRunning ? (
            <Button
              type="primary"
              shape="round"
              icon={<PauseCircleOutlined />}
              size="large"
              onClick={pauseTimer}
              className="control-button"
            >
              暂停
            </Button>
          ) : (
            <Button
              type="primary"
              shape="round"
              icon={<PlayCircleOutlined />}
              size="large"
              onClick={startTimer}
              className="control-button"
              disabled={mode === "idle" && workDuration === 0}
            >
              {mode === "idle" ? "开始" : "继续"}
            </Button>
          )}
          <Button
            shape="round"
            icon={<ReloadOutlined />}
            size="large"
            onClick={resetTimer}
            className="control-button"
          >
            重置
          </Button>
        </div>

        <div className="settings">
          <div className="setting-group">
            <label>专注时长 (分钟):</label>
            <Slider
              min={5}
              max={60}
              step={5}
              value={workDuration}
              onChange={(value) => {
                setWorkDuration(value);
                if (mode === "idle") {
                  setTimeLeft(value * 60);
                }
              }}
              disabled={mode !== "idle"}
              tooltip={{ formatter: (value) => `${value} 分钟` }}
            />
            <div className="slider-value">{workDuration} 分钟</div>
          </div>

          <div className="setting-group">
            <label>背景音效:</label>
            <div className="sound-controls">
              <Select
                value={selectedSound}
                onChange={(value) => {
                  setSelectedSound(value);
                }}
                placeholder="选择音效"
                style={{ width: 150 }}
              >
                {SOUNDS.map((sound) => (
                  <Option key={sound.id} value={sound.url}>
                    {sound.name}
                  </Option>
                ))}
              </Select>
              <Button
                type={isSoundPlaying ? "primary" : "default"}
                shape="circle"
                icon={<SoundOutlined />}
                onClick={handleSoundToggle}
                disabled={!selectedSound}
                className="sound-button"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="info-panel">
        <p>专注时间: {workDuration}分钟 &nbsp;|&nbsp; 休息时间: 5分钟</p>
        <p>提示: 完成专注时间后会自动进入休息模式</p>
      </div>
    </div>
  );
};

export default App;
